
<template>
  <div class="wrapper">
    <!-- 搜索栏 -->
    <div class="title">
      <p style="font-size: 1.2em; line-height: 100%; margin: 0; text-align: center;">特勤处一览</p>
      <br>
      <el-form :inline="true" :model="searchName" class="form" style="margin: -14px 0px 0px 0px;">
        <el-form-item label="房卡名称">
          <el-input v-model="searchName.name" placeholder="请输入tqc名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 折叠面板 -->
    <el-collapse v-model:activeNames="activeNames" accordion class="eco">
      <!-- 循环生成折叠项（每个地图对应一个折叠项） -->
      <el-collapse-item
        v-for="(tqcName, index) in tqcList"
        :key="index"
        :name="tqcName"
      >
        <!-- 折叠项标题 -->
        <template #title>
          <span>{{ tqcName }} ({{ tqcMap[tqcName]?.length || 0 }}条数据)</span>
        </template>

        <!-- 折叠内容：表格 -->
        <el-table
          :data="tqcMap[tqcName] || []"
          style="width: 100%; margin-top: 10px;"
        >


          <el-table-column prop="productionLocation" label="特勤处" width="85" />
          <el-table-column prop="level" label="等级" width="120" />
          <el-table-column prop="upgradePrerequisites" label="升级条件" width="120" />
          <el-table-column prop="requiredHafuCoins" label="需要哈夫币" width="90" />
          <el-table-column prop="totalMaterialValue" label="总材料价格" width="120" />
            <el-table-column prop="totalUpgradeCost" label="升级总花费" width="120" />

          <el-table-column prop="tqcMaterialsNeeds" label="房间包含物资" width="auto">
            <template #default="scope">
              <el-table :data="scope.row.roomContainers" style="width: 100%;">
       
                <el-table-column prop="materialName" label="所需材料" width="auto" />
                <el-table-column prop="amount" label="所需数量" width="auto" />
              </el-table>
            </template>
          </el-table-column>


              <el-table-column label="操作" width="150"> 
                <template #default="scope">
                <el-button type="primary" size="small" @click="update(scope.row.id)">编辑</el-button>
                <el-button type="danger" size="small" @click="delById(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
  </div>




<el-dialog v-model="dialogFormVisible" :title="formTitle">
  <el-form :model="tqcForm" :rules="rules" ref="tqcFormRef">
    <!-- 第一行 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="所在地图" :label-width="labelWidth" prop="productionLocation">
          <el-input v-model="tqcForm.productionLocation" placeholder="请输入所在地图" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="房名" :label-width="labelWidth" prop="level">
          <el-input v-model="tqcForm.level" placeholder="请输入房名" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第二行 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="使用地点" :label-width="labelWidth" prop="upgradePrerequisites">
          <el-input v-model="tqcForm.upgradePrerequisites" placeholder="请输入使用地点" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="价格" :label-width="labelWidth" prop="requiredHafuCoins">
          <el-input v-model.number="tqcForm.requiredHafuCoins" placeholder="请输入价格" />
        </el-form-item>
      </el-col>
    </el-row>

        <el-row>
      <el-col :span="12">
        <el-form-item label="使用地点" :label-width="labelWidth" prop="totalUpgradeCost">
          <el-input v-model="tqcForm.totalUpgradeCost" placeholder="请输入使用地点" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="价格" :label-width="labelWidth" prop="totalUpgradeCost">
          <el-input v-model.number="tqcForm.totalUpgradeCost" placeholder="请输入价格" />
        </el-form-item>
      </el-col>
    </el-row>


    <!-- 第三行：房间内包含的物资（对象数组） -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="房间内包含的物资" :label-width="150" prop="tqcMaterialsNeeds">
          <!-- 动态渲染每个物资容器 -->
          <div 
            v-for="(container, index) in tqcForm.tqcMaterialsNeeds" 
            :key="index"
            class="container-group"
          >
    

            <!-- 物资信息 -->
            <el-col :span="18">
              <el-form-item 
                :prop="'tqcMaterialsNeeds.' + index + '.materialName'" 
                :rules="{ required: true, message: '请填写材料名' }"
              >
                <el-input 
                  v-model="container.materialName" 
                  placeholder="请填写材料名"
                />
              </el-form-item>
            </el-col>

               <el-col :span="18">
              <el-form-item 
                :prop="'tqcMaterialsNeeds.' + index + '.amount'" 
                :rules="{ required: true, message: '请填写所需数量' }"
              >
                <el-input 
                  v-model="container.amount" 
                  placeholder="请填写所需数量"
                />
              </el-form-item>
            </el-col>
          </div>

        
        </el-form-item>
      </el-col>
    </el-row>


  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </span>
  </template>
  </el-form>  
</el-dialog>
     

</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import type { TqcModel,TqcMaterialsNeedsModel,TqcModelArray,TqcModelResult } from "@/api/model/model";
import { queryTqcPageApi,queryTqcByIdApi,updateApi,addApi,deleteApi,batchDeleteApi} from "@/api/tqc";
import { Plus } from '@element-plus/icons-vue'; // 按需导入图标
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps } from 'element-plus';


const dialogFormVisible = ref(false); // 初始隐藏对话框
const labelWidth = ref<number>(100)
const formTitle = ref<string>("");


 const tqcForm = ref<TqcModel>({
  productionLocation: "",
  level: 0,
  upgradePrerequisites: "",
  requiredHafuCoins: 0,
  totalMaterialValue: 0,
  totalUpgradeCost: 0,
  tqcMaterialsNeeds: [],
})
const tqcMaterialsNeedsForm = ref<TqcMaterialsNeedsModel>({
   tqcName: "",
   materialName: "",
   amount:0,
   level:0
})
//定义表单校验规则
const tqcFormRef = ref<FormInstance>()
const rules = ref<FormRules<TqcModel>>({
  productionLocation: [
    { required: true, message: '房间为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '房间名长度为2-20个字', trigger: 'blur' }
  ],
  level: [
    { required: false, message: '所在地图', trigger: 'blur' },
    {  min: 0, max: 10, message: '地图', trigger: 'blur' }
  ],
  requiredHafuCoins: [
    { required: false, message: '使用地点', trigger: 'blur' }
  ],
  upgradePrerequisites: [
    { required: true, message: '价值', trigger: 'blur' },
    {  min: 0, max: 10, message: '', trigger: 'blur' }
  ],
  totalMaterialValue: [
    { required: false, message: '单次使用消耗', trigger: 'blur' },
    {  min: 0, max: 10, message: '', trigger: 'blur' }
  ],
    totalUpgradeCost: [
    { required: false, message: '单次使用消耗', trigger: 'blur' },
    {  min: 0, max: 10, message: '', trigger: 'blur' }
  ],
     tqcMaterialsNeeds: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          return callback(new Error('所需材料不能为空'));
        }
        
        // 遍历每个容器，检查 containerInfo
        for (let i = 0; i < value.length; i++) {
          const container = value[i];
          if (!container.materialName || container.materialName === '') {
            return callback(new Error(`第 ${i+1} 个材料的信息不能为空`));
          }
          
          // 其他校验规则...
          if (container.materialName.length > 50) {
            return callback(new Error(`第 ${i+1} 个材料的信息长度不能超过50个字`));
          }
        }
        
        callback(); // 校验通过
      },
      trigger: 'blur'
    }
  ]
})
//重置校验规则
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const addTqc = () => {
  console.log("addtqc");
  dialogFormVisible.value = true
  resetForm(tqcFormRef.value) //重置校验规则
  formTitle.value = '新增防具'

  //初始化 表单数据
  tqcForm.value = {

      productionLocation: "",
      level: 0,
      upgradePrerequisites: "",
      requiredHafuCoins: 0,
      totalMaterialValue: 0,
      totalUpgradeCost: 0,
      tqcMaterialsNeeds: [{} as TqcMaterialsNeedsModel],
  }
  
}


// --------------------------------> 修改防具
//1. 查询回显
const update = async (id: number) => {
  dialogFormVisible.value = true
  formTitle.value = '修改员工'
  resetForm(tqcFormRef.value) //重置校验规则

  //发送请求, 根据ID查询员工信息
  const result = await queryTqcByIdApi(id)
  if(result.code) {
    tqcForm.value = result.data

    //做一步处理 - expr.exprDate
    // const exprList = emp.value.exprList
    // if(exprList && exprList.length>0){
    //   exprList.forEach(expr => {
    //     expr.exprDate = [expr.begin,expr.end]
    //   })
    // }
  }
}

// ----> 新增  / 修改
const save = async (form:FormInstance | undefined) => {
  //校验表单, 如果校验通过, 再提交表单
  if (!form) return
  await form.validate(async (valid, fields) => { //valid 为true, 通过 ; false, 不通过 form.validate is not a function
    if (valid) { //通过

  //     //发送异步请求保存数据
      let result ;
      if(tqcForm.value.id){ //有id, 执行修改 
        result = await updateApi(tqcForm.value)
      }else { //没有id,执行新增
        result = await addApi(tqcForm.value)
      }
      
      if(result.code){//保存成功, 提示成功信息, 关闭对话框, 重新查询
        ElMessage.success('操作成功')
        dialogFormVisible.value = false
        search()
      }else {//保存失败, 提示错误信息
        ElMessage.error(result.msg)
      }
    } else { //不通过
      ElMessage.error('表单校验失败, 不能提交')
    }
  })
}
// ----------------------------------- 删除的逻辑
const delById = (id:number) => {
  ElMessageBox.confirm('您确定要删除该数据吗?', '删除房卡',
    {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
  ).then(async () => { //点击确定按钮
    //发送请求, 删除数据
    const result = await deleteApi(id)
    if(result.code){
      ElMessage.success('删除成功')
      search()
    }else {
      ElMessage.error(result.msg)
    }
  })
}

const selectIds = ref<(number| undefined)[]>([]) //封装勾选的id
const handleSelectionChange = (val: TqcModel[]) => {
  selectIds.value = val.map(e => e.id) //map方法-遍历数组并对其中的元素进行进一步的处理, 并将结果封装到一个新的数组中
}


const batchDel = () => {
  ElMessageBox.confirm('您确定要删除该数据吗?', '删除防具',
    {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
  ).then(async () => { //点击确定按钮
    //发送请求, 删除数据
    const result = await batchDeleteApi(selectIds.value) 
    if(result.code){
      ElMessage.success('删除成功')
      search()
    }else {
      ElMessage.error(result.msg)
    }
  })
}

// 定义tq列表（需与后端返回的键名完全一致）
const tqcList = ref<string[]>(["制药台", "工作台", "指挥中心", "靶场", "技术中心", "仓库", "训练中心"]);

// 定义折叠面板激活状态（默认展开所有项，可改为 [] 折叠所有）
const activeNames = ref<string[]>(tqcList.value);


// 使用正确的类型声明 tqcMap
const tqcMap = ref<TqcModelResult>({}); // 初始值为对象，避免 undefined 报错

type SearchEmpModel = {
  name: string;
};

const searchName = ref<SearchEmpModel>({ name: "" });

const search = async () => {
  const result = await queryTqcPageApi();
  if (result.code === 200) {
    // 直接赋值整个 data 对象（键值对结构）
    tqcMap.value = result.data;
  }
};
onMounted(() => {
  search();
});
</script>

<style scoped>
    body{
        background-color: #bfa;
    }
.el-table {
  font-size: 15px;
}


    .avatar-uploader .avatar {
      width: 78px;
      height: 78px;
      display: block;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 78px;
      height: 78px;
      text-align: center;
      border: 1px dashed;
    }

</style>